package com.flyco.modules.stm.controller;

import java.math.BigDecimal;
import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.aspect.annotation.AutoLog;
import com.flyco.common.util.DateUtils;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.stm.entity.StmKpiCalendar;
import com.flyco.modules.stm.entity.StmReplenishmentItem;
import com.flyco.modules.stm.model.StmKpiCalendarModel;
import com.flyco.modules.stm.service.IStmKpiCalendarService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.flyco.common.system.base.controller.BaseController;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;

import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 业绩日历
 * @Author: flyco
 * @Date: 2021-01-06
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "业绩日历")
@RestController
@RequestMapping("/f/stm/stmKpiCalendar")
public class StmKpiCalendarController extends BaseController<StmKpiCalendar, IStmKpiCalendarService> {
    @Autowired
    private IStmKpiCalendarService stmKpiCalendarService;

    /**
     * 分页列表查询
     *
     * @param stmKpiCalendar
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "业绩日历-分页列表查询")
    @ApiOperation(value = "业绩日历-分页列表查询", notes = "业绩日历-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(StmKpiCalendar stmKpiCalendar,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<StmKpiCalendar> queryWrapper = QueryGenerator.initQueryWrapper(stmKpiCalendar, req.getParameterMap());
        Page<StmKpiCalendar> page = new Page<StmKpiCalendar>(pageNo, pageSize);
        IPage<StmKpiCalendar> pageList = stmKpiCalendarService.page(page, queryWrapper);
        if (pageList.getTotal() > 0) {
            pageList.getRecords().forEach(kpiCalendar -> {
                BigDecimal a = new BigDecimal(1);
                BigDecimal b = new BigDecimal(100);
                if ( kpiCalendar.getRate().compareTo(a) < 0 ) {
                    kpiCalendar.setRate(kpiCalendar.getRate().multiply(b));
                }
            });
        }
        return Result.ok(pageList);
    }

    /**
     * 根据年月查询列表
     *
     * @param stmKpiCalendar
     * @param req
     * @return
     */
    @AutoLog(value = "业绩日历-根据年月查询列表")
    @ApiOperation(value = "业绩日历-根据年月查询列表", notes = "业绩日历-根据年月查询列表")
    @GetMapping(value = "/listByDate")
    public Result<?> queryListByDate(StmKpiCalendar stmKpiCalendar,
                                     HttpServletRequest req) {
	 	if (oConvertUtils.isEmpty(stmKpiCalendar) || oConvertUtils.isEmpty(stmKpiCalendar.getYear()) || oConvertUtils.isEmpty(stmKpiCalendar.getMonth()))
			return Result.error("参数有误，请检查后重试！");
		LambdaQueryWrapper<StmKpiCalendar> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(StmKpiCalendar::getYear, stmKpiCalendar.getYear());
		queryWrapper.eq(StmKpiCalendar::getMonth, stmKpiCalendar.getMonth());
		List<StmKpiCalendar> calendarList = stmKpiCalendarService.list(queryWrapper);
        /*if (calendarList.size() > 0) {
            calendarList.forEach(kpiCalendar -> {
                BigDecimal a = new BigDecimal(1);
                BigDecimal b = new BigDecimal(100);
                if ( kpiCalendar.getRate().compareTo(a) < 0 ) {
                    kpiCalendar.setRate(kpiCalendar.getRate().multiply(b));
                }
            });
        }*/
        return Result.ok(calendarList);
    }

    /**
     * 添加
     *
     * @param stmKpiCalendar
     * @return
     */
    @AutoLog(value = "业绩日历-添加")
    @ApiOperation(value = "业绩日历-添加", notes = "业绩日历-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody StmKpiCalendar stmKpiCalendar) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(stmKpiCalendar.getDate());					//放入Date类型数据
        stmKpiCalendar.setYear(calendar.get(Calendar.YEAR));		//获取年份
        stmKpiCalendar.setMonth(calendar.get(Calendar.MONTH)+1);		//获取月份
        stmKpiCalendar.setDay(calendar.get(Calendar.DATE));
        stmKpiCalendar.setRate(stmKpiCalendar.getRate());
        stmKpiCalendarService.save(stmKpiCalendar);
        return Result.ok("添加成功！");
    }


    /**
     * 添加
     *
     * @param stmKpiCalendarModel
     * @return
     */
    @AutoLog(value = "业绩日历-添加")
    @ApiOperation(value = "业绩日历-添加", notes = "业绩日历-添加")
    @PostMapping(value = "/batchAdd")
    public Result<?> batchAdd(@RequestBody StmKpiCalendarModel stmKpiCalendarModel) {
        if (oConvertUtils.isEmpty(stmKpiCalendarModel) || oConvertUtils.isEmpty(stmKpiCalendarModel.getYear()) || oConvertUtils.isEmpty(stmKpiCalendarModel.getMonth())) {
            return Result.error("数据为空！");
        }
        LambdaQueryWrapper<StmKpiCalendar> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StmKpiCalendar::getYear, stmKpiCalendarModel.getYear());
        queryWrapper.eq(StmKpiCalendar::getMonth, stmKpiCalendarModel.getMonth());
        List<StmKpiCalendar> kpiCalendars = stmKpiCalendarService.list(queryWrapper);
        Map<String, List<StmKpiCalendar>> dbKpiCalendarsMap = kpiCalendars.stream().collect(Collectors.groupingBy(e -> fetchGroupKey(e)));
        List<StmKpiCalendar> addList = new ArrayList<>();
        List<StmKpiCalendar> updateList = new ArrayList<>();
        List<Date> fullDays = DateUtils.getMonthFullDay(stmKpiCalendarModel.getYear(),stmKpiCalendarModel.getMonth());
        Map<String,List<Date>> dateMap = new HashMap<>();
        fullDays.forEach(date -> {
            String week = DateUtils.date2Str(date,DateUtils.date_week.get());
            List<Date> dates = dateMap.get(week);
            if (oConvertUtils.isEmpty(dates)) {
                dates = new ArrayList<>();
            }
            dates.add(date);
            dateMap.put(week,dates);
        });
        stmKpiCalendarModel.getDetailList().forEach(item->{
            String key = item.getWeek();
            String value = item.getRate();
            log.info("key:" + key + "value:" + value);
            if (oConvertUtils.isNotEmpty(value)) {
                BigDecimal rate = new BigDecimal(value);
                List<Date> dateList = dateMap.get(key);
                //BigDecimal finalRate = rate;
                dateList.forEach(date -> {
                    StmKpiCalendar stmKpiCalendar = new StmKpiCalendar();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);					//放入Date类型数据
                    stmKpiCalendar.setYear(calendar.get(Calendar.YEAR));		//获取年份
                    stmKpiCalendar.setMonth(calendar.get(Calendar.MONTH)+1);		//获取月份
                    stmKpiCalendar.setDay(calendar.get(Calendar.DATE));
                    stmKpiCalendar.setDate(date);
                    stmKpiCalendar.setRate(rate);
                    if (dbKpiCalendarsMap.containsKey(fetchGroupKey(stmKpiCalendar))) {
                        stmKpiCalendar.setId(dbKpiCalendarsMap.get(fetchGroupKey(stmKpiCalendar)).get(0).getId());
                        updateList.add(stmKpiCalendar);
                    } else {
                        addList.add(stmKpiCalendar);
                    }
                });
            }
        });

        if (updateList.size() > 0) {
            stmKpiCalendarService.updateBatchById(updateList);
        }
        if (addList.size() > 0) {
            stmKpiCalendarService.saveBatch(addList);
        }
        return Result.ok("添加成功！");
    }

    private static String fetchGroupKey(StmKpiCalendar kpiCalendar) {
        return DateUtils.date2Str(kpiCalendar.getDate(),DateUtils.date_sdf.get());
    }

    /**
     * 编辑
     *
     * @param stmKpiCalendar
     * @return
     */
    @AutoLog(value = "业绩日历-编辑")
    @ApiOperation(value = "业绩日历-编辑", notes = "业绩日历-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody StmKpiCalendar stmKpiCalendar) {
        stmKpiCalendarService.updateById(stmKpiCalendar);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "业绩日历-通过id删除")
    @ApiOperation(value = "业绩日历-通过id删除", notes = "业绩日历-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        stmKpiCalendarService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "业绩日历-批量删除")
    @ApiOperation(value = "业绩日历-批量删除", notes = "业绩日历-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.stmKpiCalendarService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "业绩日历-通过id查询")
    @ApiOperation(value = "业绩日历-通过id查询", notes = "业绩日历-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        StmKpiCalendar stmKpiCalendar = stmKpiCalendarService.getById(id);
        return Result.ok(stmKpiCalendar);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param stmKpiCalendar
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StmKpiCalendar stmKpiCalendar) {
        return super.exportXls(request, stmKpiCalendar, StmKpiCalendar.class, "业绩日历");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, StmKpiCalendar.class);
    }

}
